//////////////////////////////////////////////////////////////////////////////////
//	PageControl.cs
//
//	Written by Cosic Nadin and Franz Thomas Reinisch FH-Joanneum ITM06
//  
//////////////////////////////////////////////////////////////////////////////////



using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Timers;
using System.Configuration;
namespace WiiFlipChart
{
    class PageControl
    {
        private int currentPageNumber;
        private String workPath;
        private String pageName;
        private Bitmap currentPage;
        private Rectangle rect;
        private Graphics graphImage;

        private System.Timers.Timer timer;
        private bool changePagePossible = true;


       
        public event EventHandler CurrentPageChanged;

        
        /// <summary>
        /// the public event to show the page was changed
        /// </summary>
        /// <param name="ea"></param>
        protected void OnCurrentPageChanged(EventArgs ea)
        {
            if (CurrentPageChanged != null)
            {
                CurrentPageChanged(this, ea);
            }
        }



       
        static readonly PageControl instance = new PageControl();

        
        public static PageControl Instance
        {
            get
            {
                return instance;
            }
        }

        
        /// <summary>
        /// Draw a new white page
        /// </summary>
        private void DrawNewPage() 
        {

            currentPage = new Bitmap(Controller.Instance.getDrawFieldSizeX(), Controller.Instance.getDrawFieldSizeY());
            graphImage = Graphics.FromImage(currentPage);
            rect = new Rectangle(0, 0, Controller.Instance.getDrawFieldSizeX(), Controller.Instance.getDrawFieldSizeY());
            graphImage.FillRectangle(new SolidBrush(Color.White), rect);
    
        }


        /// <summary>
        /// Constructor of Pagecontrol
        /// Try to find an existing Page
        /// </summary>

        PageControl()
        {

            //Read the config
            AppSettingsReader config = new AppSettingsReader();
            workPath = (String)config.GetValue("workPath", typeof(String));
           
            workPath = @workPath;
            
           
            pageName = "page";
            currentPageNumber = 1;

            InitTimer();
            
                //Open a Page if it existing
                try
                {

                    FileStream fs = new FileStream(workPath + pageName + currentPageNumber + ".bmp", FileMode.Open, FileAccess.Read);
                    currentPage = new Bitmap(fs);
                    fs.Close();

                    //Fire the Event that a new current Picture  
                    OnCurrentPageChanged(EventArgs.Empty);
                }

                catch
                {
                    //no existing page make new one
                    DrawNewPage();

                    //Fire the Event that a new current Picture  
                    OnCurrentPageChanged(EventArgs.Empty);

                }

        }


        /// <summary>
        /// this timmer is to prevent error cause of to fast switch  among the pages
        /// </summary>
        private void InitTimer()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 500;
            timer.Elapsed += new ElapsedEventHandler(this.OnTimerTickEvent);

        }
       

        /// <summary>
        /// Make it possible to save a page again
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnTimerTickEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Stop();
            changePagePossible = true;
          
        }




        /// <summary>
        /// 
        /// </summary>
        /// <returns> return the current page </returns>

        public Bitmap getCurrentPage()
        { 
           return currentPage;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns> return the current pagenumber</returns>
        public int getCurrentPageNumer()
        {
            return currentPageNumber;
        }



        /// <summary>
        /// 
        ///try to load an existing next page, otherwise create a new one
        /// </summary>
        public void showNextPage()
        {
            
            if(changePagePossible == false)
            {
               //Console.WriteLine("to fast");
                return;
            }

            this.savePage();
            
            currentPageNumber++;


            // Try to find next page
            try
            {
                FileStream fs = new FileStream(workPath + pageName + currentPageNumber + ".bmp", FileMode.Open, FileAccess.Read);
                currentPage = new Bitmap(fs);
                fs.Close();

                //Fire the Event that a new current Picture  
                OnCurrentPageChanged(EventArgs.Empty);
                

                //Refresh form to draw the Current Picture
                DrawBoard.ActiveForm.Invalidate();


                
                


            }

            catch
            {
                
                DrawNewPage();
                
                //Fire the Event that a new current Picture  
                OnCurrentPageChanged(EventArgs.Empty);

                DrawBoard.ActiveForm.Invalidate();
            }

            // Start timer to avoid to fast pageChange
            changePagePossible = false; this.timer.Start();


        }


       
        /// <summary>
        /// Show the previous page
        /// </summary>
        public void showPrevPage()
        {

            if (changePagePossible == false)
            {
                Console.WriteLine("to fast");
                return;
            }
            
            
            
            
            if (currentPageNumber == 1)
            { 
               //if you are on the first page do  nothing
                return ;

            }

            this.savePage();

            // Try to find previous page
            currentPageNumber--;
            
            try
            {
                FileStream fs = new FileStream(workPath + pageName + currentPageNumber + ".bmp", FileMode.Open, FileAccess.Read);
                currentPage = new Bitmap(fs);
                fs.Close();

                //Fire the Event that a new current Picture  
                OnCurrentPageChanged(EventArgs.Empty);

                //Refresh form to draw the Current Picture
                DrawBoard.ActiveForm.Invalidate();

            }

            
            
            catch // If ther a failure to load the Picture
            {
               
                DrawNewPage();

                //Fire the Event that a new current Picture  
                OnCurrentPageChanged(EventArgs.Empty);

                DrawBoard.ActiveForm.Invalidate();
            }

            // Start protecttimer to avoid to fast pageChange
            changePagePossible = false; this.timer.Start();

        
        }


        private void savePage()
        {

            //Look if the director exists
            if (Directory.Exists(workPath) == false)
            { 
                
            // There is no Directory - it will be created
             Directory.CreateDirectory(workPath);
            }



            try
            {
                currentPage.Save(workPath + pageName + currentPageNumber + ".bmp");

            }
            catch
            {

                MessageBox.Show("error saving file");

            }



        }

    
    }
}
